import { useState, useContext } from 'react'
import { View, Text, Textarea } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { AppContext } from '../../store'
import { getLocale } from '../../i18n'
import './index.scss'

function Settings() {
  const { state, setLocale, setApiKey } = useContext(AppContext)
  const i18n = getLocale(state.locale)
  const [showApiKeyInput, setShowApiKeyInput] = useState(false)
  const [apiKeyInput, setApiKeyInput] = useState(state.apiKey)

  const handleLanguageChange = () => {
    const newLocale = state.locale === 'zh' ? 'en' : 'zh'
    setLocale(newLocale as 'zh' | 'en')
    Taro.showToast({
      title: newLocale === 'zh' ? '已切换至中文' : 'Switched to English',
      icon: 'success',
      duration: 1500
    })
  }

  const handleSaveApiKey = async () => {
    if (!apiKeyInput.trim()) {
      Taro.showToast({
        title: i18n.chat.inputEmpty,
        icon: 'none'
      })
      return
    }

    const trimmedKey = apiKeyInput.trim()
    console.log('保存 API Key，长度:', trimmedKey.length)
    console.log('API Key 前10位:', trimmedKey.substring(0, 10))
    
    // 显示加载提示
    Taro.showLoading({
      title: state.locale === 'zh' ? '验证中...' : 'Validating...'
    })
    
    try {
      // 测试 API Key 是否有效
      const testResponse = await Taro.request({
        url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${trimmedKey}`
        },
        data: {
          model: 'deepseek-r1-0528',
          messages: [{ role: 'user', content: '你好' }],
          stream: false,
          max_tokens: 10
        },
        timeout: 10000
      })
      
      console.log('API 测试响应:', testResponse)
      
      if (testResponse.statusCode === 200) {
        // API Key 有效，保存
        setApiKey(trimmedKey)
        setShowApiKeyInput(false)
        
        Taro.hideLoading()
        Taro.showToast({
          title: state.locale === 'zh' ? 'API Key 验证成功' : 'API Key validated',
          icon: 'success'
        })
        
        // 验证是否保存成功
        setTimeout(() => {
          const savedKey = Taro.getStorageSync('apiKey')
          console.log('验证保存后的 API Key 长度:', savedKey.length)
        }, 100)
      } else {
        throw new Error(`验证失败: ${testResponse.statusCode}`)
      }
    } catch (error: any) {
      console.error('API Key 验证失败:', error)
      Taro.hideLoading()
      Taro.showModal({
        title: state.locale === 'zh' ? 'API Key 无效' : 'Invalid API Key',
        content: state.locale === 'zh' 
          ? '无法连接到阿里云百炼服务，请检查 API Key 是否正确。\n\n错误信息: ' + (error.errMsg || error.message || '未知错误')
          : 'Cannot connect to Alibaba Cloud Bailian service. Please check your API Key.\n\nError: ' + (error.errMsg || error.message || 'Unknown error'),
        showCancel: true,
        confirmText: state.locale === 'zh' ? '仍然保存' : 'Save Anyway',
        cancelText: state.locale === 'zh' ? '重新输入' : 'Re-enter',
        success: (res) => {
          if (res.confirm) {
            // 用户选择仍然保存
            setApiKey(trimmedKey)
            setShowApiKeyInput(false)
            Taro.showToast({
              title: i18n.chat.saveApiKey + ' ' + i18n.common.confirm,
              icon: 'success'
            })
          }
        }
      })
    }
  }

  const handleShowAbout = () => {
    Taro.showModal({
      title: i18n.settings.about,
      content: state.locale === 'zh' 
        ? '故物有灵 v1.0.0\n\n让文物会说话，以3D展示和AI对话推动文化传承。\n\n© 2025 故物有灵团队'
        : 'Living Artifacts v1.0.0\n\nLet cultural relics speak through 3D display and AI dialogue.\n\n© 2025 Living Artifacts Team',
      showCancel: false,
      confirmText: i18n.common.confirm
    })
  }

  return (
    <View className='settings-container'>
      {/* 头部 */}
      <View className='settings-header'>
        <View className='header-bg' />
        <View className='header-content'>
          <Text className='header-icon'>⚙️</Text>
          <Text className='header-title'>{i18n.settings.title}</Text>
        </View>
      </View>

      {/* 设置列表 */}
      <View className='settings-body'>
        {/* 语言设置 */}
        <View className='settings-section'>
          <Text className='section-title'>{i18n.settings.language}</Text>
          <View className='setting-item' onClick={handleLanguageChange}>
            <View className='setting-item-left'>
              <Text className='setting-icon'>🌐</Text>
              <Text className='setting-label'>{i18n.settings.language}</Text>
            </View>
            <View className='setting-item-right'>
              <Text className='setting-value'>
                {state.locale === 'zh' ? i18n.settings.languageZh : i18n.settings.languageEn}
              </Text>
              <Text className='setting-arrow'>›</Text>
            </View>
          </View>
        </View>

        {/* API设置 */}
        <View className='settings-section'>
          <Text className='section-title'>{i18n.chat.settingsTitle}</Text>
          <View className='setting-item' onClick={() => setShowApiKeyInput(!showApiKeyInput)}>
            <View className='setting-item-left'>
              <Text className='setting-icon'>🔑</Text>
              <Text className='setting-label'>{i18n.settings.apiKey}</Text>
            </View>
            <View className='setting-item-right'>
              <Text className='setting-value'>
                {state.apiKey ? '••••••••' : state.locale === 'zh' ? '未设置' : 'Not Set'}
              </Text>
              <Text className='setting-arrow'>›</Text>
            </View>
          </View>

          {showApiKeyInput && (
            <View className='api-key-input-wrapper'>
              <View className='input-container'>
                <Textarea
                  className='api-key-input'
                  value={apiKeyInput}
                  placeholder={i18n.chat.apiKeyPlaceholder}
                  onInput={(e) => setApiKeyInput(e.detail.value)}
                  onFocus={() => console.log('Input focused')}
                  onBlur={() => console.log('Input blurred')}
                  maxlength={200}
                  autoHeight
                  focus
                  adjustPosition
                  cursorSpacing={30}
                  placeholderStyle='color: #999;'
                  showConfirmBar={false}
                />
              </View>
              <View className='input-buttons'>
                <View 
                  className='btn-cancel'
                  onClick={() => {
                    setShowApiKeyInput(false)
                    setApiKeyInput(state.apiKey)
                  }}
                >
                  <Text className='btn-text'>{i18n.common.cancel}</Text>
                </View>
                <View className='btn-save' onClick={handleSaveApiKey}>
                  <Text className='btn-text'>{i18n.chat.saveApiKey}</Text>
                </View>
              </View>
              <Text className='input-hint'>
                {state.locale === 'zh' 
                  ? '💡 提示：API Key可在阿里云百炼控制台获取（https://bailian.console.aliyun.com）'
                  : '💡 Tip: Get your API Key from Alibaba Cloud Bailian Console (https://bailian.console.aliyun.com)'}
              </Text>
              <Text className='input-hint'>
                {i18n.chat.apiKeyHint}
              </Text>
            </View>
          )}
        </View>

        {/* 关于 */}
        <View className='settings-section'>
          <View className='setting-item' onClick={handleShowAbout}>
            <View className='setting-item-left'>
              <Text className='setting-icon'>ℹ️</Text>
              <Text className='setting-label'>{i18n.settings.about}</Text>
            </View>
            <View className='setting-item-right'>
              <Text className='setting-arrow'>›</Text>
            </View>
          </View>
        </View>
      </View>

      {/* 底部装饰 */}
      <View className='settings-footer'>
        <Text className='footer-text'>
          {state.locale === 'zh' ? '故物有灵 · 让文物会说话' : 'Living Artifacts · Let Relics Speak'}
        </Text>
      </View>
    </View>
  )
}

export default Settings

